package com.example.springboot.service.impl;

import com.example.springboot.document.Product;
import com.example.springboot.repository.ProductRepository;
import com.example.springboot.service.ProductSearchService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @Description: 产品搜索实现
 * @Author wenlinyu
 * @Date: 2021/2/23 15:57
 * @Version 1.0
 */
@Service
public class ProductSearchServiceImpl extends BaseSearchServiceImpl<Product> implements ProductSearchService {

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private ElasticsearchTemplate elasticsearchTemplate;
    @Autowired
    private ProductRepository productRepository;

    @Override
    public void save(Product... products) {
        elasticsearchTemplate.putMapping(Product.class);
        if (products != null && products.length > 0) {
            logger.info("【保存索引】：{}", productRepository.saveAll(Arrays.asList(products)));
        }
    }

    @Override
    public void delete(String id) {
        productRepository.deleteById(id);
    }

    @Override
    public void deleteAll() {
        productRepository.deleteAll();
    }

    @Override
    public Product getById(String id) {
        return productRepository.findById(id).get();
    }

    @Override
    public List<Product> getAll() {
        List<Product> list = new ArrayList<>();
        productRepository.findAll().forEach(list::add);
        return list;
    }
}
